<?php

namespace App\Http\Middleware;

use Closure;

class AdminPageSidebar
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 取权限名
        $adminPermissionNames = $request->user()->permissions->pluck('name')->toArray();

        // 发到所有视图
        view()->share('userPermissionNames', $adminPermissionNames);

        // 所有权限与模块
        $allModules = [
            [
                'title' => '后台权限',
                'list'  => [
                    [
                        'name'  => 'permission module',
                        'icon'  => 'fa fa-user',
                        'url'   => '/admin/admins',
                        'title' => '用户',
                    ],
                ],
            ]
        ];

        // 过滤当前管理员的权限与模块配置
        $adminModules = [];
        foreach ($allModules as $k => $submodules) {
            foreach ($submodules['list'] as $module) {
                if (in_array($module['name'], $adminPermissionNames)) {
                    $adminModules[$k]['list'][] = $module;
                }
            }
            if (isset($adminModules[$k]['list'])) {
                $adminModules[$k]['title'] = $submodules['title'];
            }
        }

        view()->share('adminModules', $adminModules);

        return $next($request);
    }
}
